package com.rex.editor.view;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.SparseArrayCompat;

import com.base.common.model.bean.KeyValue;
import com.base.common.utils.ColorUtils;
import com.base.common.utils.DensityUtil;
import com.base.common.utils.DialogUtils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.utils.span.SpanUtils;
import com.base.common.view.widget.PasteEditText;
import com.base.common.view.widget.imageView.GlideImageView;
import com.base.gsyvideoplayer.model.SwitchVideoModel;
import com.base.gsyvideoplayer.tools.GSYSampleVideoUtils;
import com.base.gsyvideoplayer.view.SampleVideo;
import com.rex.editor.common.FilesUtils;
import com.rex.editor.common.Utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import static com.rex.editor.common.FilesUtils.getVideoThumbnail;


public class RichEditText extends LinearLayout implements TextWatcher, View.OnKeyListener, PasteEditText.OnPasteCallback {

    private int hp, wp;//高度和宽度

    public RichEditText(Context context) {
        this(context, null);
    }

    public RichEditText(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RichEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RichEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setOrientation(VERTICAL);//
        TextView textView = getTextView();
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, DensityUtil.getDimens(com.base.common.R.dimen.font_16));
        listData.clear();
        if (isEdit) textView.setHint(hint);
        addView(textView);

        if (attrs == null) return;
        //get layout_height
        String height = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_height");
        String width = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_width");

        if (!height.equals(ViewGroup.LayoutParams.MATCH_PARENT + "") && !height.equals(ViewGroup.LayoutParams.WRAP_CONTENT + "")) {
            int[] systemAttrs = {android.R.attr.layout_height};
            TypedArray a = context.obtainStyledAttributes(attrs, systemAttrs);
            hp = a.getDimensionPixelSize(0, ViewGroup.LayoutParams.WRAP_CONTENT);
            a.recycle();
        }

        if (!width.equals(ViewGroup.LayoutParams.MATCH_PARENT + "") && !width.equals(ViewGroup.LayoutParams.WRAP_CONTENT + "")) {
            int[] systemAttrs = {android.R.attr.layout_width};
            TypedArray a = context.obtainStyledAttributes(attrs, systemAttrs);
            wp = a.getDimensionPixelSize(0, ViewGroup.LayoutParams.WRAP_CONTENT);
            a.recycle();
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.EXACTLY) {
            wp = widthSize;
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            hp = heightSize;
        } else {
            //如果高度设置了wrap_content，则取最大的子View高
            int maxChildHeight = 0;
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
                maxChildHeight = Math.max(maxChildHeight, child.getMeasuredHeight() + layoutParams.topMargin + layoutParams.bottomMargin);
            }
            hp = maxChildHeight;
        }
    }

    private boolean isEdit = true;//是否可编辑
    private boolean isPaste = false;//是否执行了黏贴操作
    private int start, end;//编辑的开始和结束位置
    private boolean isADD = false;//输入文字

    private GSYSampleVideoUtils videoUtils;

    public static final String REMIND = "remind";//@联系人
    public static final String GAMBIT = "gambit";//话题
    public static final String MATCHS = "matchs";//赛事
    public static final char RS = 30;//开始的标记  可点击的文字  这些标记不会显示
    public static final char US = 31;//结束的标记
    private boolean isAddImageEnable = true;//是否可以添加图片
    private boolean isAddVideoEnable = true;//是否可以添加视频

    private boolean isAddGambitEnable = true;//是否可以添加话题
    private boolean isAddRemindEnable = true;//是否可以添加@联系人

    private String hint = "请输入内容";

    private int onclickTextColor = 0xff3392FF;
    //视频缩略图
    private boolean isNeedAutoPosterUrl = true;

    //                      str带有RS 和US标记 , data为id, name类型   只添加不删除，故有很多多余的，
    private SparseArrayCompat<KeyValue<String, String, String>> listData = new SparseArrayCompat<>();//话题 @ 赛事的集合

    private OnClickImageTagListener mOnClickImageTagListener;
    private OnClickTextTagListener onClickTextTagListener;
    private OnAddImageCallback onAddImageCallback;//添加图片的回调
    private TextWatcher textWatcher;

    private float mSpacingAdd = 0;
    private float mSpacingMult = 0;

    public void setOnClickImageTagListener(OnClickImageTagListener mOnClickImageTagListener) {
        this.mOnClickImageTagListener = mOnClickImageTagListener;
    }

    public void setTextChangedListener(TextWatcher textWatcher) {
        this.textWatcher = textWatcher;
    }

    public void setOnAddImageCallback(OnAddImageCallback onAddImageCallback) {
        this.onAddImageCallback = onAddImageCallback;
    }

    //自动为视频添加缩略图
    public void setNeedAutoPosterUrl(boolean needAutoPosterUrl) {
        isNeedAutoPosterUrl = needAutoPosterUrl;
    }

    public void setHint(String hint) {
        this.hint = hint;
        if (getChildCount() == 1 && getChildAt(0) instanceof EditText) {
            EditText editText = (EditText) getChildAt(0);
            editText.setHint(hint);
        }
    }

    public void setEdit(boolean edit) {
        isEdit = edit;
        for (int i = 0; i < getChildCount(); i++) {
            if (getChildAt(i) instanceof EditText) {
                EditText editText = (EditText) getChildAt(i);
                if (edit) {
                    // 可以编辑可以点击，显示光标：
                    editText.setFocusable(true);
                    editText.setCursorVisible(true);
                    editText.setClickable(true);
                    editText.setFocusableInTouchMode(true);
                    editText.requestFocus();
                } else {
                    //(不可编辑但可点击,隐藏光标)
                    editText.setCursorVisible(false);
                    editText.setFocusable(false);
                    editText.setClickable(true);
                    editText.setFocusableInTouchMode(false);
                }
            } else if (getChildAt(i) instanceof ImageView) {
                if (edit) {
                    setOnLongClick(getChildAt(i));
                } else {
                    getChildAt(i).setOnLongClickListener(null);
                }
            }


        }
    }

    public void setVideoUtils(GSYSampleVideoUtils videoUtils) {
        this.videoUtils = videoUtils;
    }

    public void setOnClickTextTagListener(OnClickTextTagListener onClickTextTagListener) {
        this.onClickTextTagListener = onClickTextTagListener;
    }

    public void setAddGambitEnable(boolean addGambitEnable) {
        isAddGambitEnable = addGambitEnable;
    }

    public void setAddImageEnable(boolean addImageEnable) {
        isAddImageEnable = addImageEnable;
    }

    public void setAddRemindEnable(boolean addRemindEnable) {
        isAddRemindEnable = addRemindEnable;
    }

    public void setAddVideoEnable(boolean addVideoEnable) {
        isAddVideoEnable = addVideoEnable;
    }

    public void setSpacingAdd(float mSpacingAdd) {
        this.mSpacingAdd = mSpacingAdd;
        if (mSpacingAdd > 0) {
            for (int i = 0; i < getChildCount(); i++) {
                if (getChildAt(i) instanceof EditText) {
                    EditText editText = (EditText) getChildAt(i);
                    float mSpacingMult = editText.getLineSpacingMultiplier();
                    editText.setLineSpacing(mSpacingAdd, mSpacingMult);
                }
            }
        }
    }

    public void setSpacingMult(float mSpacingMult) {
        this.mSpacingMult = mSpacingMult;
        if (mSpacingMult > 0) {
            for (int i = 0; i < getChildCount(); i++) {
                if (getChildAt(i) instanceof EditText) {
                    EditText editText = (EditText) getChildAt(i);
                    float mSpacingAdd = editText.getLineSpacingExtra();
                    editText.setLineSpacing(mSpacingAdd, mSpacingMult);
                }
            }
        }
    }

    public void setText(String str) {
        removeAllViews();
        listData.clear();
        TextView textView = getTextView();
        addView(textView);
        isPaste = true;//走黏贴路线
        if (str != null && str.startsWith("\n")) {
            textView.setText(str.substring(1));
        } else {
            textView.setText(str);
        }

        if (!isEdit) {
            Editable editable = textView.getEditableText();
            onTextChanged(editable, 0, 0, editable.length());
            afterTextChanged(editable);
        }

    }

    public int getLength() {
        int count = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);

            if (view instanceof EditText) {
                EditText editText = (EditText) view;
                count += editText.getText().length();
            }
        }
        return count;
    }

    public String getTextHtml() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (view instanceof EditText) {
                EditText editText = (EditText) view;
                sb.append(getEditTextString(editText));
            } else if (view instanceof GlideImageView) {
                GlideImageView imageView = (GlideImageView) view;
                String url = imageView.getImageUrl();
                if (url.length() > 0) {
                    sb.append(getImageHtml(url));
                }
            } else if (view instanceof SampleVideo) {
                SampleVideo video = (SampleVideo) view;
                String url = video.getSourceUrl();
                if (url != null) {
                    sb.append(getVideoHtml(url));
                }
            }
        }

        return sb.toString();
    }

    private String getEditTextString(EditText editText) {
        StringBuilder sb = new StringBuilder();
        String str = editText.getText().toString();

        str = str.replaceAll("\n", "<br>");
        str = str.replaceAll(" ", "&nbsp;");

        int start = str.indexOf(RS);
        int end = str.indexOf(US);
        String sss = "";
        //检查可点击文字
        if (listData.size() > 0 && start >= 0) {
            if (start > 0) {
                String ss1 = str.substring(0, start);
                sb.append(ss1);
            }
            while (end > start && start > -1) {
                String sst = str.substring(start, end + 1);
                KeyValue<String, String, String> keyValue = listData.get(sst.hashCode());
                if (keyValue != null) {
                    sb.append(getLabelHtml(keyValue.getDesc(), keyValue.getValue(), keyValue.getKey()));
                }
                start = str.indexOf(RS, end + 1);
                if (start > end) {
                    sb.append(str.substring(end + 1, start));
                    end = str.indexOf(US, start);
                }
            }
            if (end > 0 && end + 1 < str.length()) {
                String ss1 = str.substring(end + 1);
                sb.append(ss1);
            }

            sss = sb.toString();
            sss = sss.replaceAll(String.valueOf(RS), "");
            sss = sss.replaceAll(String.valueOf(US), "");
        } else {
            sss = editText.getText().toString();
        }

        return sss;
    }


    /**
     * @param str 可以带html标签的字符串
     */
    public void insertText(String str) {
        EditText textView = getFocusedEditText();
        isPaste = true;//走黏贴路线
        if (textView != null) {
            int start = textView.getSelectionStart();
            if (start < 0) start = textView.getText().length();
            textView.getText().insert(start, str);
        }
    }


    public String getLabelHtml(String type, String data, String content) {
        return "<label  name=\"" + type + "\"   data=\"" + data + "\"    style=\"color:" + ColorUtils.getColorStringInt(onclickTextColor) + "\">" + content + "</label>&nbsp;";
    }

    public String getImageHtml(String url) {
        return "<img src=\"" + url + "\" alt=\"picvision\" style=\"margin-top:10px;width:100%;height:200px;object-fit:cover;\" />";
    }

    public String getVideoHtml(String videoUrl) {
        String posterUrl = "";
        if (isNeedAutoPosterUrl) {
            Bitmap videoThumbnail = getVideoThumbnail(videoUrl);
            if (videoThumbnail != null) {
                String videoThumbnailUrl = FilesUtils.saveBitmap(videoThumbnail);
                if (!TextUtils.isEmpty(videoThumbnailUrl)) {
                    posterUrl = videoThumbnailUrl;
                }
            }
        }

        String custom = "height=\"200px\" " + " style=\"margin-top:10px;width:100%;\"";
        return "<video controls=\"controls\"  controlsList=\"nodownload\"  poster=\"" + posterUrl + "\" src=\"" + videoUrl + "\" " + custom + "></video>";
    }


    /**
     * 插入  @青菜紫红   @某人
     *
     * @param str
     */
    public void insertRemind(@NonNull String str, String id) {
        if (!str.startsWith("@")) str = "@" + str;
        insertOnClickText(REMIND, id, str);
    }

    /**
     * 插入  #青菜紫红   话题
     * <p>
     *
     * @param str
     */
    public void insertGambit(String str, String id) {
        if (!str.startsWith("#")) str = "#" + str;
        insertOnClickText(GAMBIT, id, str);
    }

    public void insertOnClickText(String type, String data, String content) {
        insertText(getLabelHtml(type, data, content));
    }


    /**
     * 插入图片
     *
     * @param url
     */
    public void insertImage(String url) {
        insertText(getImageHtml(url));
    }


    /**
     * 插入视频
     *
     * @param videoUrl
     */
    public void insertVideo(String videoUrl) {
        insertText(getVideoHtml(videoUrl));
    }

    private EditText getTextView() {
        if (isEdit) {
            PasteEditText editText = new PasteEditText(getContext());
            editText.setLayoutParams(new LayoutParams(-1, -2));
            editText.setBackground(null);
            editText.addTextChangedListener(this);
            editText.setOnKeyListener(this);
            editText.setOnPasteCallback(this);

            if (mSpacingAdd == 0) mSpacingAdd = editText.getLineSpacingExtra();
            if (mSpacingMult == 0) mSpacingMult = editText.getLineSpacingMultiplier();
            editText.setLineSpacing(mSpacingAdd, mSpacingMult);
            // 可以编辑可以点击，显示光标：
            editText.setFocusable(true);
            editText.setCursorVisible(true);
            editText.setClickable(true);
            editText.setFocusableInTouchMode(true);
            editText.requestFocus();
            return editText;
        } else {
            PasteEditText editText = new PasteEditText(getContext());
            editText.setLayoutParams(new LayoutParams(-1, -2));
            editText.setBackground(null);
            editText.setOnPasteCallback(this);
            if (mSpacingAdd == 0) mSpacingAdd = editText.getLineSpacingExtra();
            if (mSpacingMult == 0) mSpacingMult = editText.getLineSpacingMultiplier();
            editText.setLineSpacing(mSpacingAdd, mSpacingMult);

            //(不可编辑但可点击,隐藏光标)
            editText.setCursorVisible(false);
            editText.setFocusable(false);
            editText.setFocusableInTouchMode(false);
            editText.setClickable(true);
            return editText;
        }
    }


    private GlideImageView getImageView() {
        GlideImageView imageView = new GlideImageView(getContext());
        imageView.setLayoutParams(new LayoutParams(-1, -2));
        imageView.setAdjustViewBounds(true);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setBackgroundColor(0xfff8f8f8);
        return imageView;
    }

    /**
     * 插入图片
     *
     * @param url 图片地址
     */
    private void insertImageView(String url) {
        url = url.replace("\\\"", "");
        if (onAddImageCallback != null) onAddImageCallback.insertImage(url);
        if (isAddImageEnable) {
            GlideImageView imageView = getImageView();
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            layoutParams.height = DensityUtil.getDimens(com.base.common.R.dimen.dp_200);
            imageView.setLayoutParams(layoutParams);
            imageView.loadUrl(url, false);
            imageView.setPadding(0, 10, 0, 0);
            insertView(imageView);
            final String finalUrl = url;
            imageView.setOnClickListener(new OnClickCheckedUtil() {
                @Override
                public void onClicked(View view) {
                    if (mOnClickImageTagListener != null) {
                        mOnClickImageTagListener.onClick(view, finalUrl);
                    }
                }
            });

            if (isEdit) {
                setOnLongClick(imageView);
            }
        }
    }

    private void setOnLongClick(final View view) {
        if (view == null) return;
        if (view.getContext() instanceof Activity) {
            view.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Activity activity = (Activity) view.getContext();
                    DialogUtils.showSimpleDialog(activity, false, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            removeView(view);
                            dialog.dismiss();
                        }
                    }, "是否删除？");
                    return true;
                }
            });
        }

    }

    /**
     * 插入视频
     *
     * @param url    视频地址
     * @param poster 视频缩略图
     */
    private void insertVideo(String url, String poster) {
        if (poster == null) poster = "";
        url = url.replace("\\\"", "");
        if (onAddImageCallback != null) onAddImageCallback.insertImage(url);

        if (isAddVideoEnable) {
            poster = poster.replace("\\\"", "");
            SampleVideo sampleVideo = new SampleVideo(getContext());
            sampleVideo.setLayoutParams(new LayoutParams(-1, DensityUtil.getDimens(com.base.common.R.dimen.dp_200)));
            sampleVideo.setPadding(0, 10, 0, 0);

            sampleVideo.setMoreScale(false);
            sampleVideo.setSwitchSize(false);
            sampleVideo.setTitle(false);
            sampleVideo.setFullscreen(true);
            if (videoUtils != null) {
                List<SwitchVideoModel> list = new ArrayList<>();
                list.add(new SwitchVideoModel("视频", url));
                videoUtils.initView(sampleVideo);
                videoUtils.initUrl(list);
                if (TextUtils.isEmpty(poster)) {
                    if (url.startsWith("http")) {
                        videoUtils.loadFirstFrameCoverForVideo(url);
                    } else {
                        Bitmap videoThumbnail = getVideoThumbnail(url);
                        if (videoThumbnail != null) {
                            String videoThumbnailUrl = FilesUtils.saveBitmap(videoThumbnail);
                            if (!TextUtils.isEmpty(videoThumbnailUrl)) {
                                poster = videoThumbnailUrl;
                                videoUtils.loadFirstFrameCover(poster);
                            }
                        }
                    }
                } else {
                    videoUtils.loadFirstFrameCover(poster);
                }

            }
            insertView(sampleVideo);
        }
    }

    private void insertView(@NonNull View view) {
        EditText editText = getFocusedEditText();

        if (editText != null) {
            Editable str = editText.getText();
            int startFocu = editText.getSelectionStart();//光标所在位置

            int index = 0;//插入的位置
            if (str.length() == 0 || startFocu == 0) {
                index = indexOfChild(editText);          //在前面插入
                if (index == 0) editText.setHint("");
                if (index < 0) index = 0;
                addView(view, index);

            } else {
                index = indexOfChild(editText) + 1;//在后面插入
                if (index < 0) index = 0;
                addView(view, index);

                if (startFocu < 0) startFocu = str.length();

                if (startFocu > 0 && startFocu <= str.length()) {
                    TextView textView = getTextView();
                    textView.setText(str.subSequence(startFocu, str.length()));
                    editText.getText().delete(startFocu, str.length());
                    addView(textView, index + 1);
                }

            }
        }
    }

    //控件内部调用插入
    private void insertCharSequence(CharSequence str) {
        if (str == null) str = "";

        EditText textView = getFocusedEditText();

        if (textView != null && textView.getEditableText() != null) {
            textView.setMovementMethod(LinkMovementMethod.getInstance());

            int start = textView.getSelectionStart();
            textView.requestFocus();
            textView.getText().insert(start, str);
            textView.setSelection(start + str.length());
        }
    }


    /**
     * 控件内部调用插入
     *
     * @param str 插入的实际内容  @联系人
     */
    private void insertOnClickText(String str) {
        if (str == null) str = "";
        final KeyValue<String, String, String> keyValue = listData.get(str.hashCode());
        if (keyValue != null) {

            if (REMIND.equals(keyValue.getDesc()) && !isAddRemindEnable) {
                return;
            }
            if (GAMBIT.equals(keyValue.getDesc()) && !isAddGambitEnable) {
                return;
            }

            int start = str.indexOf(RS);
            int end = str.indexOf(US);
            if (end > start && start > -1 && end < str.length()) {
                SpanUtils spanUtils = new SpanUtils();
                spanUtils.append(str.substring(start, start + 1)).setForegroundColor(0x00ffffff);
                spanUtils.append(str.substring(start + 1, end)).setForegroundColor(onclickTextColor).setClickSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        if (onClickTextTagListener != null)
                            onClickTextTagListener.onClick(widget.getContext(), keyValue.getKey(), keyValue.getDesc(), keyValue.getValue());
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
//                        super.updateDrawState(ds);
                        ds.setUnderlineText(false);
                    }
                });
                spanUtils.append(str.substring(end, end + 1)).setForegroundColor(0x00ffffff);
                insertCharSequence(spanUtils.create());
            }
        }

    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
            EditText editText = getFocusedEditText();
            if (editText != null) {
                LogUtil.d("KeyEvent", event.getAction() + " ");
                int co = editText.getSelectionStart();
                if (co > 0) {
                    return checkedOnClickTextDelete(editText, true);
                }
                int index = indexOfChild(editText);
                if (index > 0) {
                    View viewLast = getChildAt(index - 1);
                    if (viewLast instanceof EditText) {
                        Editable str = editText.getText();
                        EditText editText1 = (EditText) viewLast;
                        int startFo = editText1.getText().toString().length();
                        //下面的没有删除完毕
                        if (str.length() > 0) {
                            editText1.getText().append(str);
                        }
                        editText1.requestFocus();
                        editText1.setSelection(startFo);
                        removeView(editText);
                    } else {
                        removeView(viewLast);
                    }
                } else {
                    if (index == 0) {
                        if (getChildCount() > 1) {
                            editText.setHint("");
                        } else {
                            editText.setHint(hint);
                        }
                        String str = editText.getText().toString();
                        if (co < str.length()) {
                            boolean bb = checkedOnClickTextDelete(editText, false);
                            if (bb) return true;
                            if (co > -1) editText.getText().delete(co, co + 1);
                        } else {
                            if (getChildCount() > 1) {
                                View viewNext = getChildAt(index + 1);
                                if (viewNext instanceof EditText) {
                                    EditText editText1 = (EditText) viewNext;
                                    editText.getText().append(editText1.getText().subSequence(0, editText1.getText().length()));
                                }
                                removeView(viewNext);
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    //监听黏贴
    @Override
    public void onPaste() {
        isPaste = true;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (textWatcher != null) {
            textWatcher.beforeTextChanged(s, start, count, after);
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //添加
        if (before == 0 && count > 0) {
            int end = start + count;
            this.start = start;
            this.end = end;
            isADD = true;
        }
        //删除
//        if (count == 0 && before > 0) {
//            checkedOnClickTextDelete();
//        }
        if (textWatcher != null) {
            textWatcher.onTextChanged(s, start, before, count);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

        if (isPaste) {
            isPaste = false;
            String str = s.subSequence(start, end).toString();
            s.delete(start, end);
            str = str.replaceAll("&nbsp;", " ");
            str = str.replaceAll("<p><br></p>", "<br>");
            str = str.replaceAll("\n", "<br>");
            Document doc = Jsoup.parse(str);
            Elements elementsP = doc.select("body");
            for (Element element : elementsP) {
                List<Node> list = element.childNodes();
                if (list != null) {
                    for (Node node : list) {
                        initNode(node);
                    }
                }

            }
        } else {
            moveText(s);
        }

        if (textWatcher != null) {
            textWatcher.afterTextChanged(s);
        }
    }

    /**
     * 移动要插入的内容到指定的位置
     */
    private void moveText(Editable s) {
        if (isADD) isADD = false;
        else return;
        if (start == 0) return;

        //判断插入的位置是否合法,不可以在可点击文字的中间
        boolean isMove = false;//是否需要移动
        int oldStart = start;
        int oldEnd = end;

        String str = s.toString();
        //        s2     s1      s4     s3
        //     ___RS-----US__ ___RS-----US_____RS
        int s1 = str.lastIndexOf(US, start);//从删除位置往前查找
        int s2 = str.lastIndexOf(RS, start);
        int s3 = str.indexOf(US, end);//从删除的位置往后查找
        int s4 = str.indexOf(RS, end);
        if (s2 > s1 && (s3 < s4 || (s4 == -1 && s3 != -1))) {
            isMove = true;
            //在标签中间
            start = s3;
            end = start + oldEnd - oldStart;
        }

        if (isMove) {
            //这是插入字符串
            CharSequence ss = s.subSequence(oldStart, oldEnd);
            int si = s.length();
            s.delete(oldStart, oldEnd);//删除新加入的内容，重新添加
            EditText editText = getFocusedEditText();
            if (editText != null) {
                if (start >= s.length()) {
                    s.append(ss);
                    editText.setSelection(s.length());
                } else {
                    s.insert(start, ss);
                    editText.setSelection(start + ss.length());
                }
            }

        }


    }


    private void initNode(Node node) {
        if (node instanceof TextNode) {
            insertCharSequence(node.toString().replaceAll("\n", ""));
        } else if (node instanceof Element) {
            Element element = (Element) node;
            String tag = element.nodeName();
            switch (tag) {
                case "div":
                    List<Node> list = element.childNodes();
                    if (list != null) {
                        EditText textView = getFocusedEditText();
                        if (textView.getSelectionStart() > 0) {
                            textView.append("\n");
                        }
                        for (Node nodeChild : list) {
                            initNode(nodeChild);
                        }
                    }
                    break;
                case "img":
                    String src = element.attr("src");
                    insertImageView(src);
                    break;
                case "video":
                case "iframe":
                    src = element.attr("src");
                    String poster = element.attr("poster");
                    insertVideo(src, poster);
                    break;


                case "br":
                    EditText textView = getFocusedEditText();
                    textView.append("\n");
                    break;
                case "label":
                    String str = element.text();
                    String name = element.attr("name");
                    String data = element.attr("data");
                    name = name.replace("\\\"", "");
                    data = data.replace("\\\"", "");
                    if (UIUtils.isNotEmpty(name) && UIUtils.isNotEmpty(data)) {
                        str = RS + str + US;//加上开始和结束标记
                        listData.put(str.hashCode(), new KeyValue<>(str, data, name));
                        insertOnClickText(str);
                    } else {
                        insertCharSequence(str);
                    }

                    break;
                case "strong":
                case "span":
                    str = element.text();
                    insertCharSequence(str);
                    break;
                case "p":
                    list = element.childNodes();
                    if (list != null) {
                        textView = getFocusedEditText();
                        if (textView.getSelectionStart() > 0) {
                            textView.append("\n");
                        }
                        for (Node nodeChild : list) {
                            initNode(nodeChild);
                        }
                    }
                    break;
            }

        }
    }


    public EditText getFocusedEditText() {
        EditText editText = null;
        for (int i = getChildCount() - 1; i >= 0; i--) {
            if (getChildAt(i) instanceof EditText) {
                editText = (EditText) getChildAt(i);
                if (isEdit) {
                    if (editText.isFocused()) return editText;
                } else {
                    return editText;
                }
            }
        }
        return editText;
    }


    /**
     * 可以点击的文定要一起删除
     *
     * @param editText
     * @param before   true  往前删除
     */
    private boolean checkedOnClickTextDelete(EditText editText, boolean before) {
        //检查删除的位置是不是在RS US 中间
        Editable editable = editText.getText();
        String str = editable.toString();
        int start = editText.getSelectionStart();
        int end = editText.getSelectionEnd();

        //        s2     s1      s4     s3
        //     ___RS-----US__ ___RS-----US_____RS
        int s1 = str.lastIndexOf(US, start);//从删除位置往前查找
        int s2 = str.lastIndexOf(RS, start);

        int s3 = str.indexOf(US, end);//从删除的位置往后查找
        int s4 = str.indexOf(RS, end);

        int indexStart = 0, indexEnd = 0;
        if (s2 > s1 && (s3 < s4 || (s4 == -1 && s3 != -1))) {
            //删除的位置在标签中间，删除整个标签的内容
            indexStart = s2;
            indexEnd = s3 + 1;
            editable.delete(indexStart, indexEnd);
            return true;
        } else {
            //删除的位置在标签之外
            if (before) {
                int inEnd = end == editable.length() ? end - 1 : end;
                char ch = editable.charAt(inEnd);
                if (ch == RS) {
                    s1 = str.lastIndexOf(US, start - 1);//从删除位置往前查找
                    s2 = str.lastIndexOf(RS, start - 1);
                    if (s2 < s1 && s2 > -1) {
                        indexStart = s2;
                        indexEnd = end;
                        if (indexStart >= 0)
                            editable.delete(indexStart, indexEnd);
                        return true;
                    }
                } else if (ch == US) {
                    indexStart = s2;
                    indexEnd = end;
                    if (indexStart >= 0)
                        editable.delete(indexStart, indexEnd);
                    return true;
                } else if (s2 < s1 && s2 > -1) {
                    if (end == s1 + 1) {
                        indexStart = s2;
                        indexEnd = end;
                        if (indexStart >= 0)
                            editable.delete(indexStart, indexEnd);
                        return true;
                    }
                }
            } else {
                if (s4 < s3 && s4 > -1) {
                    if (end == s4 - 1 || s2 == s4) {
                        indexStart = end;
                        indexEnd = s3 + 1;
                        if (indexStart >= 0)
                            editable.delete(indexStart, indexEnd);
                        return true;
                    }
                }
            }

        }

        return false;
    }

    //缩略图功能会产生本地文件可调用此方法清理
    public void clearLocalRichEditorCache() {
        listData.clear();
        FilesUtils.clearLocalRichEditorCache();
    }

    // 获取html本地的地址 方便上传的时候转为在线的地址
    public List<String> getAllSrcAndHref(String html) {
        return Utils.getHtmlSrcOrHrefList(html);
    }

    public interface OnAddImageCallback {
        void insertImage(String url);
    }

    public interface OnClickTextTagListener {
        void onClick(Context context, String str, String type, String data);
    }

    public interface OnClickImageTagListener {
        void onClick(View view, String url);
    }
}
